package com.example.android.thread.init;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.example.androidthread.R;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 实现Callable 重写call方法，配合FutureTask
 * Callable一般用于有返回结果的非阻塞的执行方法
 * 同步非阻塞。 https://blog.csdn.net/weixin_48321993/article/details/131475435
 *
 */
public class FutureTaskActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thread);

        //1. 创建MyCallable
        MyCallable myCallable = new MyCallable();
        //2. 创建FutureTask，传入Callable
        FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
        //3. 创建Thread线程
        Thread t1 = new Thread(futureTask);
        //4. 启动线程
        t1.start();
        //5. 做一些操作
        //6. 要结果
        int count = 0;
        try {
            count = futureTask.get();
        } catch (Exception e) {
           e.printStackTrace();
        }
        System.out.println("总和为：" + count);

    }


    static class MyCallable implements Callable<Integer> {

        @Override
        public Integer call() {
            int count = 0;
            for (int i = 0; i < 100; i++) {
                count += i;
            }
            return count;
        }
    }

}
